package Dao.Impl;

import Dao.FinancialProductTaskDAO;
import Model.FinancialProductTask;
import Util.DbConnector;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class FinancialProductTaskDAOImpl implements FinancialProductTaskDAO {
    private static final Logger logger = LogManager.getLogger(FinancialProductTaskDAOImpl.class);
    private final QueryRunner queryRunner = new QueryRunner();

    public FinancialProductTaskDAOImpl() {
    }

    @Override
    public void addFinancialProductTask(FinancialProductTask task) {
        String sql = "INSERT INTO financial_product_tasks (userId, productId, purchaseAmount, expectedEarnings, purchaseDate, maturityDate, status) VALUES (?, ?, ?, ?, ?, ?, ?)";
        try (Connection connection = DbConnector.getConnection()) {
            queryRunner.update(connection, sql,
                    task.getUserId(),
                    task.getProductId(),
                    task.getPurchaseAmount(),
                    task.getExpectedEarnings(),
                    task.getPurchaseDate(),
                    task.getMaturityDate(),
                    task.getStatus());
            logger.info("添加理财产品任务成功，任务ID: " + task.getId());
        } catch (SQLException e) {
            logger.error("添加理财产品任务失败，任务ID: " + task.getId(), e);
        }
    }

    @Override
    public List<FinancialProductTask> getAllFinancialProductTasks() {
        String sql = "SELECT * FROM financial_product_tasks";
        try (Connection connection = DbConnector.getConnection()) {
            return queryRunner.query(connection, sql, new BeanListHandler<>(FinancialProductTask.class));
        } catch (SQLException e) {
            logger.error("获取所有理财产品任务失败", e);
            return null;
        }
    }

    @Override
    public void updateFinancialProductTask(FinancialProductTask task) {
        String sql = "UPDATE financial_product_tasks SET status = ?, maturityDate = ? WHERE id = ?";
        try (Connection connection = DbConnector.getConnection()) {
            queryRunner.update(connection, sql, task.getStatus(), task.getMaturityDate(), task.getId());
            logger.info("更新理财产品任务成功，任务ID: " + task.getId());
        } catch (SQLException e) {
            logger.error("更新理财产品任务失败，任务ID: " + task.getId(), e);
        }
    }

    @Override
    public void deleteFinancialProductTask(int id) {
        String sql = "DELETE FROM financial_product_tasks WHERE id = ?";
        try (Connection connection = DbConnector.getConnection()) {
            queryRunner.update(connection, sql, id);
            logger.info("删除理财产品任务成功，任务ID: " + id);
        } catch (SQLException e) {
            logger.error("删除理财产品任务失败，任务ID: " + id, e);
        }
    }
}